<template>
  <div>
    <div class="top-wrap bg-white box-shadow">
      <template v-if="roleType === 'admin'">
        <el-button type="primary" @click="handleDownloadExcel">下载EXCEL</el-button>
      </template>
      <template v-else>
        <el-button type="primary" @click="handleGoAddContract">添加合同</el-button>
        <el-button type="primary" plain>下载合同模板</el-button>
      </template>
      <el-input
        placeholder="合同编号/客户名称/社会信用码"
        v-model="searchVal"
        style="width: 30%; float: right; min-width: 250px"
        v-search-throttle="handleSearch"
        @clear="handleSearch"
        clearable
      ></el-input>
    </div>

    <div class="list-wrap bg-white box-shadow clear-float">
      <div class="select-wrap">
        <el-date-picker
          v-model="timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleSelectChange"
        >
        </el-date-picker>
        <el-select v-model="typeVal" placeholder="合同类型" clearable class="select-item" @change="handleSelectChange">
          <el-option v-for="item in typeOpts" :key="item" :label="item" :value="item"></el-option>
        </el-select>
        <el-select
          v-model="statusVal"
          placeholder="合同状态"
          clearable
          class="select-item"
          @change="handleSelectChange"
        >
          <el-option v-for="item in statusOpts" :key="item" :label="item" :value="item"></el-option>
        </el-select>
        <template v-if="roleType === 'admin'">
          <el-select
            v-model="belongVal"
            placeholder="合同归属"
            clearable
            class="select-item"
            @change="handleSelectChange"
          >
            <el-option v-for="item in belongOpts" :key="item.value" :label="item.name" :value="item.value"></el-option>
          </el-select>

          <el-select
            v-model="SellerId"
            placeholder="申请销售"
            clearable
            class="select-item"
            @change="handleSelectChange"
          >
            <el-option
              v-for="item in sellerOpts"
              :key="item.AdminId"
              :label="item.RealName"
              :value="item.AdminId"
            ></el-option>
          </el-select>
        </template>
      </div>

      <el-table :data="list" v-loading="loading"  border>
        <el-table-column key="合同编号" align="center" prop="ContractCode" label="合同编号" width="165">
          <template #default="scope">
            <router-link :to="`/contract/detail/${scope.row.ContractId}`" class="constract-sn">{{
              scope.row.ContractCode
            }}</router-link>
          </template>
        </el-table-column>
        <el-table-column key="客户名称" align="center" prop="CompanyName" label="客户名称"></el-table-column>
        <el-table-column
          key="社会信用码"
          align="center"
          prop="CreditCode"
          label="社会信用码"
          width="170"
        ></el-table-column>
        <el-table-column key="销售" align="center" prop="SellerName" label="销售"></el-table-column>
        <el-table-column key="合同类型" align="center" prop="ContractType" label="合同类型"></el-table-column>
        <el-table-column key="合同有效期" align="center" label="合同有效期" width="200">
          <template #default="scope">
            <span style="display: inline-block; white-space: nowrap">{{ scope.row.StartDateStr }}</span>
            ~
            <span style="display: inline-block; white-space: nowrap">{{ scope.row.EndDateStr }}</span>
          </template>
        </el-table-column>
        <el-table-column key="合同金额" align="center" prop="Price" label="合同金额"></el-table-column>
        <el-table-column key="合同状态" align="center" prop="Status" label="合同状态">
          <template #default="scope">
            <span
              :style="{
                color: scope.row.Status === '已驳回' ? '#FF0000' : null
              }"
              >{{ scope.row.Status }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          key="更新时间"
          align="center"
          prop="ModifyTimeStr"
          label="更新时间"
          width="160"
        ></el-table-column>
        <el-table-column key="seller操作" label="操作" align="center">
          <template #default="scope">
            <span
              class="operate-btn"
              @click="handleOperation(item.key, scope.row)"
              v-for="item in filterOperationBtns(scope.row.Status)"
              :key="item.name"
              :style="{ color: item.color }"
            >
              {{ item.name }}
            </span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="total,prev, pager, next"
        :current-page="page"
        @current-change="handlePageChange"
        :page-size="pageSize"
        :total="total"
        style="float: right; margin-top: 20px"
      ></el-pagination>
    </div>

    <!-- 查看套餐 -->
    <ViewService
      :list="viewServiceList"
      :show="showViewServiceDialog"
      @handleCloseViewService="handleCloseViewService"
    ></ViewService>
  </div>
</template>

<script lang="ts">
import ViewService from './components/ViewService.vue'
import { defineComponent, reactive, toRefs, ref } from 'vue'
import { apiContractList } from '@/api/contract'
import { apiSellerList } from '@/api/common'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default defineComponent({
  name: 'ContractList',
  components: {
    ViewService
  },
  setup() {
    const store = useStore()
    const router=useRouter()

    const typeOpts: string[] = ['新签合同', '续约合同', '补充协议'] //合同类型选项
    const statusOpts: string[] = ['待提交', '待审批', '已撤回', '已审批', '已驳回', '已作废'] //合同状态选项
    const belongOpts = [
      { name: 'FICC', value: 1 },
      { name: '权益', value: 2 }
    ] //合同归属选项
    let sellerOpts = ref([]) //申请销售选项
    let viewServiceList = ref([]) //查看套餐数据
    let showViewServiceDialog = ref(false) //是否展示查看套餐弹窗

    let state = reactive({
      roleType: store.state.user.data.RoleTypeCode, //用户身份类型
      typeVal: '', //合同状态值
      statusVal: '', //合同状态值
      belongVal: '', //合同归属值
      SellerId: '', //申请销售值
      searchVal: '', //搜索值
      timeRange: '', //筛选时间
      list: [], //合同列表数据
      loading:false,//表格loading
      page: 1, //当前第几页
      pageSize: 10, //每页数据数
      total: 0 //合同列表总数
    })

    /**
     * 处理列表操作显示按钮
     * return [{name:'编辑',key:'edit',color:""}]
     */
    type optObj = {
      name: string
      key: string
      color?: string
    }
    const filterOperationBtns = (status: string) => {
      let arr: optObj[] = []
      // admin用户只有 查看套餐和下载（已审批可下载）操作
      const roleType = store.state.user.data.RoleTypeCode
      if (roleType === 'admin') {
        if (status === '已审批') {
          arr = [
            { name: '查看套餐', key: 'viewPackage' },
            { name: '下载', key: 'download' }
          ]
        } else {
          arr = [{ name: '查看套餐', key: 'viewPackage' }]
        }
      }
      if (roleType === 'ficc_seller' || roleType === 'rai_seller') {
        if (status === '待提交') {
          arr = [
            { name: '提交审批', key: 'submitApproval' },
            { name: '编辑', key: 'edit' },
            { name: '删除', key: 'submitApproval', color: '#ff0000' }
          ]
        }
        if (status === '待审批') {
          arr = [
            { name: '查看套餐', key: 'viewPackage' },
            { name: '撤回申请', key: 'backApply' }
          ]
        }
        if (status === '已撤回') {
          arr = [
            { name: '查看套餐', key: 'viewPackage' },
            { name: '修改合同', key: 'modifyConstract' },
            { name: '删除', key: 'delete', color: '#ff0000' }
          ]
        }
        if (status === '已审批') {
          arr = [
            { name: '查看套餐', key: 'viewPackage' },
            { name: '作废合同', key: 'cancelConstract' },
            { name: '下载', key: 'download' }
          ]
        }
        if (status === '已驳回') {
          arr = [
            { name: '查看套餐', key: 'viewPackage' },
            { name: '驳回理由', key: 'rejectReason' },
            { name: '申请重审', key: 'applyRetrial' },
            { name: '删除', key: 'delete', color: '#ff0000' }
          ]
        }
        if (status === '已作废') {
          arr = [
            { name: '复制模板', key: 'copy' },
            { name: '删除', key: 'delete', color: '#ff0000' }
          ]
        }
      }
      return arr
    }

    //操作
    const handleOperation = (type: string, item: any) => {
      // 查看套餐
      if (type === 'viewPackage') {
        viewServiceList.value = item.Service
        showViewServiceDialog.value = true
      }

      //下载合同
      if(type==='download'){
        const a=document.createElement('a')
        a.href = item.FileUrl + "?response-content-type=application/octet-stream";
        a.setAttribute('download', 'download')
        a.style.display = 'none' //a标签隐藏
        document.body.appendChild(a)
        a.click()
      }
    }

    //管理员下载excel
    const handleDownloadExcel = async () => {
      let token = store.state.user.data.Authorization
      let obj = {
        ContractType: state.typeVal,
        ContractStatus: state.statusVal,
        ProductId: state.belongVal ? state.belongVal : 0,
        ModifyStartTime: state.timeRange[0] ? `${state.timeRange[0]} 00:00:00` : '',
        ModifyEndTime: state.timeRange[1] ? `${state.timeRange[1]} 23:59:59` : '',
        SellerId: '',
        Keyword: state.searchVal
      }
      let paramStr = ''
      for (let key in obj) {
        paramStr = `${paramStr}&${key}=${obj[key]}`
      }

      const a = document.createElement('a')
      a.href = `${import.meta.env.VITE_APP_API_URL}/contract/export?${token}${paramStr}`
      a.setAttribute('download', 'download')
      a.style.display = 'none' //a标签隐藏
      document.body.appendChild(a)
      a.click()
    }

    //选项变化
    const handleSelectChange = () => {
      state.searchVal = ''
      getContractList()
    }

    //搜索
    const handleSearch = () => {
      state.typeVal = ''
      state.statusVal = ''
      state.belongVal = ''
      state.timeRange = ''
      state.page = 1
      getContractList()
    }

    //点击换页
    const handlePageChange = (page: number) => {
      state.page = page
      getContractList()
    }

    //获取合同列表数据
    const getContractList = async () => {
      state.loading=true
      let res = await apiContractList({
        CurrentIndex: state.page,
        PageSize: state.pageSize,
        ContractType: state.typeVal,
        ContractStatus: state.statusVal,
        ProductId: Number(state.belongVal),
        ModifyStartTime: state.timeRange[0] || '',
        ModifyEndTime: state.timeRange[1] || '',
        Keyword: state.searchVal,
        SellerId: state.SellerId
      })
      state.loading=false
      if (res.Ret === 200) {
        state.list = res.Data.List
        state.total = res.Data.Paging.Totals
      }
    }

    //获取申请销售列表(仅管理员需要获取)
    const getSellerList = async () => {
      let res = await apiSellerList()
      if (res.Ret === 200) {
        sellerOpts.value = res.Data.List
      }
    }

    //关闭查看套餐弹窗
    const handleCloseViewService = () => {
      showViewServiceDialog.value = false
      viewServiceList.value = []
    }

    //跳转添加合同
    const handleGoAddContract=()=>{
      router.push('/contract/add')
    }

    getContractList()
    if (state.roleType === 'admin') {
      getSellerList()
    }
    return {
      viewServiceList,
      showViewServiceDialog,
      sellerOpts,
      typeOpts,
      statusOpts,
      belongOpts,
      handleSearch,
      handleOperation,
      handlePageChange,
      handleSelectChange,
      filterOperationBtns,
      handleDownloadExcel,
      handleCloseViewService,
      handleGoAddContract,
      ...toRefs(state)
    }
  }
})
</script>

<style lang="scss" scoped>
.top-wrap {
  padding: 20px 30px;
}

.list-wrap {
  margin-top: 20px;
  padding: 30px;
  min-height: 70vh;
  .constract-sn {
    cursor: pointer;
    color: #409eff;
  }
  .operate-btn {
    font-size: 14px;
    display: inline-block;
    color: #409eff;
    cursor: pointer;
    margin: 0 3px;
    white-space: nowrap;
  }
}
.select-wrap {
  .select-item {
    margin-right: 20px;
    margin-bottom: 20px;
    width: 12%;
    min-width: 110px;
  }
}
</style>
